package com.aw.puzzle.dropboxdiet.support;

import com.aw.puzzle.dropboxdiet.Activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;

/**
 * User: gmc
 * Date: 29/01/11
 */
public class ActivityCollectorFromConsole implements ActivityCollector {

    private static final String PATTERN_FOR_VALID_ACTIVITY = "^[a-z]+(\\-?[a-z]+)* \\-?[0-9]+";

    public List<Activity> getAllActivities() {
        Scanner scanner = new Scanner(System.in);
        String numberOfActivitiesStr = scanner.nextLine();
        int numberOfActivities = getNumberOfActivities(numberOfActivitiesStr);
        List<Activity> activities = new ArrayList();
        for (int i = 0; i < numberOfActivities; i++) {
            String activityInfo = scanner.nextLine();
            Activity activity = getActivityFrom(activityInfo);
            activities.add(activity);
        }
        return activities;
    }

    private int getNumberOfActivities(String numberOfActivitiesStr) {
        int numberOfActivites = -1;
        try {
            numberOfActivites = Integer.parseInt(numberOfActivitiesStr);
        } catch (Throwable throwable) {
            throw new IllegalArgumentException("<"+numberOfActivitiesStr + "> is not valid number");
        }
        if (numberOfActivites < 1 || numberOfActivites > 50) {
            throw new IllegalArgumentException("<"+numberOfActivites + "> must be in the range of 1-50");
        }
        return numberOfActivites;
    }

    private Activity getActivityFrom(String activityInfo) {
        if (!activityInfo.matches(PATTERN_FOR_VALID_ACTIVITY)) {
            throw new IllegalStateException("The activity Info:" + activityInfo + " is not valid. \nActivity names will use only lowercase ASCII letters and the dash (-) character.\nActivities or food items and its respective calorie impact must be separated by a space.");
        }
        StringTokenizer st = new StringTokenizer(activityInfo);
        String activityName = st.nextToken();
        int calorieValue = Integer.parseInt(st.nextToken());
        return new Activity(activityName, calorieValue);
    }
}
